/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.dressingsocial.service;

import com.dressingsocial.model.Dressing;
import com.dressingsocial.model.User;
import com.dressingsocial.repository.DressingRepository;
import com.dressingsocial.repository.UserRepository;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author hayate
 */
@Service
public class DressingService {

    @Resource
    private DressingRepository dressingRepository;

    @Resource
    private UserRepository userRepository;

    @Transactional
    public List<Dressing> findLatestDressings() {
        return dressingRepository.findAll();
    }
    
    @Transactional
    public List<Dressing> findHotestDressings() {
        return dressingRepository.findAll();
    }
    @Transactional
    public Dressing create(Dressing dressing) {
        Dressing createdDressing = dressing;
        return dressingRepository.save(createdDressing);
    }

    @Transactional
    public Dressing findById(Long id) {
        return dressingRepository.findOne(id);
    }

    @Transactional
    public List<Dressing> findOwnDressingsById(Long id) {

        User user = userRepository.findOne(id);
        if (!user.getDressings().isEmpty()) {
            return user.getDressings();
        } else {
            return new ArrayList<Dressing>();
        }
    }
    
    @Transactional
    public Dressing update(Dressing dressing) {
       
        if(dressingRepository.findOne(dressing.getId()) != null) {
            Dressing updatedDressing = dressing;
            return dressingRepository.save(updatedDressing);
        } else {
            dressing.setId(new Long(0));
            return dressing;
        }
    }

    @Transactional
    public Dressing delete(Long id) {
        Dressing deletedDressing = dressingRepository.findOne(id);
        dressingRepository.delete(deletedDressing);
        return deletedDressing;
    }
}
